package com.system.common.service.image.impl;

import com.system.common.service.image.ImageService;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Service
public class ImageServiceImpl implements ImageService {

    private static final Random RANDOM = new Random();
    private static final String RAND_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";    //随机产生的字符串

    private static final int WIDTH = 80;    //图片宽
    private static final int HEIGHT = 30;    //图片高
    private static final int LINE_SIZE = 40;    //干扰线数量
    private static final int RANDOM_NUM = 4;    //随机产生字符数量

    @Override
    public BufferedImage buildImage(StringBuilder codeBuilder) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR);
        // 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        Graphics g = image.getGraphics();
        g.fillRect(0, 0, WIDTH, HEIGHT);
        g.setFont(new Font(null, Font.ROMAN_BASELINE, 18));
        g.setColor(Color.BLACK);
        // 绘制干扰线
        for (int i = 0; i <= LINE_SIZE; i++) {
            drowLine(g);
        }
        // 绘制随机字符
        for (int i = 0; i < RANDOM_NUM; i++) {
            drowString(g, codeBuilder, i);
        }
        g.dispose();
        return image;
    }

    /*
     * 绘制字符串
     */
    private void drowString(Graphics g, StringBuilder randomBuilder, int i) {
        Font font = new Font(null, Font.CENTER_BASELINE, 24);
        g.setFont(font);
        g.setColor(Color.BLACK);
        String rand = getRandomString();
        randomBuilder.append(rand);
        g.translate(RANDOM.nextInt(3), RANDOM.nextInt(3));
        g.drawString(rand, 16 * i + 2, 18);
    }

    /*
     * 绘制干扰线
     */
    private void drowLine(Graphics g) {
        int x1 = RANDOM.nextInt(WIDTH);
        int y1 = RANDOM.nextInt(HEIGHT);
        int x2 = RANDOM.nextInt(HEIGHT);
        int y2 = RANDOM.nextInt(HEIGHT);
        g.drawLine(x1, y1, x1 + x2, y1 + y2);
    }

    /*
     * 获取随机的字符
     */
    public String getRandomString() {
        return String.valueOf(RAND_STRING.charAt(RANDOM.nextInt(RAND_STRING.length())));
    }

}
